/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import { Project } from '@ohos/hvigor';

import { ModuleType } from '../../enum/module-type-enum.js';
import { LegacyModuleModelImpl } from '../module/legacy-module-model-impl.js';

import { CoreProjectModelImpl } from './core-project-model-impl.js';
import { BundleType } from '../../const/common-const.js';

export class LegacyProjectModelImpl extends CoreProjectModelImpl {
  constructor(project: Project) {
    super(project);
  }

  initSubProject(): void {
    const subModules = this.project.getSubModules();
    subModules.forEach((module, name) => {
      this.subModels.set(name, new LegacyModuleModelImpl(module, this));
    });
  }

  getDefaultBundleName(): string {
    let defaultBundleName = '';
    try {
      this.subModels.forEach((value) => {
        if (value.getModuleType() === ModuleType.Entry) {
          const legacyModuleModel: LegacyModuleModelImpl = value as LegacyModuleModelImpl;
          defaultBundleName = legacyModuleModel.getSourceSetByTargetName().getLegacyModuleTargetRes().getConfigJsonOpt().app.bundleName;

          // end for each loop
          throw new Error('End loop.');
        }
      });
    } catch (e) {
      // do nothing
    }
    return defaultBundleName;
  }

  getBundleType(): string {
    for (const [, module] of this.subModels.entries()) {
      if (module.getModuleType() === ModuleType.Entry) {
        const legacyModuleModel: LegacyModuleModelImpl = module as LegacyModuleModelImpl;
        return legacyModuleModel.isInstallFree() ? BundleType.ATOMIC_SERVICE : BundleType.APP;
      }
    }
    return BundleType.APP;
  }

  isFaMode(): boolean {
    return true;
  }
}
